package com.egao.common.module.guidance.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.component.minio.service.MinioService;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.company.utils.CompanyUtil;
import com.egao.common.module.credits.CreditsConstants;
import com.egao.common.module.credits.entity.Credits;
import com.egao.common.module.credits.service.CreditsService;
import com.egao.common.module.guidance.entity.Lecture;
import com.egao.common.module.guidance.mapper.LectureMapper;
import com.egao.common.module.guidance.service.LectureService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

/**
 * 就业讲座接口实现类
 *
 * @author pyx
 */
@Service
public class LectureServiceImpl extends ServiceImpl<LectureMapper, Lecture> implements LectureService {

    @Autowired
    private StudentService studentService;
    @Autowired
    private MinioService minioService;
    @Autowired
    private CreditsService creditsService;

    @Value("${minio.endpoint}")
    private String url;

    @Override
    public List<Lecture> listPage(PageParam<Lecture> pageParam, Integer userId) {
        //处理举办时间段数据
        pageParam = (PageParam<Lecture>) CompanyUtil.putApplyTime(pageParam);

        Integer studentId = null;
        Student student = studentService.getByUserId(userId);
        if (student != null) {
            studentId = student.getId();
        }

        //如果card为0查询所有讲座信息
        if ("0".equals(pageParam.getPageData().get("card"))) {
            studentId = null;
        }

        List<Lecture> list = baseMapper.listPage(pageParam, studentId);

        return list;
    }

    @Override
    public JsonResult insertLecture(Lecture lecture) {
        if (lecture == null) {
            throw new ParameterException("参数对象为空");
        }

        if (StrUtil.isBlank(lecture.getTitle())) {
            throw new ParameterException("标题不能为空");
        }
        if (lecture.getStartTime() == null) {
            throw new ParameterException("举办时间不能为空");
        }
        if (lecture.getEndTime() == null) {
            throw new ParameterException("截止时间不能为空");
        }
        if (lecture.getApplyEndTime() == null) {
            throw new ParameterException("报名截止时间不能为空");
        }
        if (lecture.getApplyNum() == null) {
            throw new ParameterException("报名人数限制不能为空");
        }
        if (lecture.getApplyPass() == null) {
            throw new ParameterException("是否报名直接通过状态不能为空");
        }
        if (StrUtil.isBlank(lecture.getHoldAddress())) {
            throw new ParameterException("举办地点不能为空");
        }
        if (StrUtil.isBlank(lecture.getContent())) {
            throw new ParameterException("正文不能为空");
        }

        if (baseMapper.insert(lecture) > 0) {
            // 添加项目学分
            creditsService.saveCredits(new Credits(CreditsConstants.TYPE_lECTURE, lecture.getId(), lecture.getTitle(), lecture.getCredits()));
            return JsonResult.ok("添加成功");
        }

        return JsonResult.error("添加失败");
    }

    @Override
    public JsonResult updateLecture(Lecture lecture) {
        if (lecture == null) {
            throw new ParameterException("参数对象为空");
        }

        if (StrUtil.isBlank(lecture.getTitle())) {
            throw new ParameterException("标题不能为空");
        }
        if (lecture.getStartTime() == null) {
            throw new ParameterException("举办时间不能为空");
        }
        if (lecture.getEndTime() == null) {
            throw new ParameterException("截止时间不能为空");
        }
        if (lecture.getApplyEndTime() == null) {
            throw new ParameterException("报名截止时间不能为空");
        }
        if (lecture.getApplyNum() == null) {
            throw new ParameterException("报名人数限制不能为空");
        }
        if (lecture.getApplyPass() == null) {
            throw new ParameterException("是否报名直接通过状态不能为空");
        }
        if (StrUtil.isBlank(lecture.getHoldAddress())) {
            throw new ParameterException("举办地点不能为空");
        }
        if (StrUtil.isBlank(lecture.getContent())) {
            throw new ParameterException("正文不能为空");
        }

        if (baseMapper.updateById(lecture) > 0) {
            // 修改项目学分
            creditsService.saveCredits(new Credits(CreditsConstants.TYPE_lECTURE, lecture.getId(), lecture.getTitle(), lecture.getCredits()));
            return JsonResult.ok("修改成功");
        }

        return JsonResult.error("修改失败");
    }

    @Override
    public JsonResult deleteLecture(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }
        Lecture lecture = getById(id);

        if (removeById(id)) {
            // 删除项目学分
            creditsService.deletedCredits(new Credits(CreditsConstants.TYPE_lECTURE, lecture.getId(), lecture.getTitle(), lecture.getCredits()));
            return JsonResult.ok("删除成功");
        }

        return JsonResult.error("删除失败");
    }

    @Override
    public Lecture getId(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        QueryWrapper<Lecture> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Integer count = baseMapper.selectCount(wrapper);

        if (count != 1) {
            throw new ParameterException("详情不存在");
        }

        Lecture lecture = baseMapper.selectById(id);
        return lecture;
    }

    @Override
    public JsonResult qr(Lecture lecture) {
        if (lecture == null) {
            throw new ParameterException("参数对象为空");
        }

        //二维码对应跳转地址
//        String content = "https://wx2.zuel.edu.cn/uc/api/oauth/index?redirect=http://jyzx.zuel.edu.cn/mobile/lecture/loading&appid=200200424131910103&lectureId=" + lecture.getId();

        //测试环境模拟code传入,跳过微信认证
        String content = "http://192.168.1.5:8081/mobile/lecture/loading?code=2021&&lectureId=" + lecture.getId();
        //生成二维码
        BufferedImage generate = QrCodeUtil.generate(content, 300, 300);

        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(generate, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            MultipartFile multipartFile = new MockMultipartFile("file", "file.jpg", "text/plain", input);

            //存在二维码至minio
            JsonResult jsonResult = minioService.uploadPath(multipartFile, "lecture/qr");

            //保存二维码图片地址
            url = (String)jsonResult.get("url");
            lecture.setQrUrl(url);
            baseMapper.updateById(lecture);

            return JsonResult.ok("已生成二维码");
        } catch (IOException e) {
            return JsonResult.error("二维码生成失败");
        }

    }
}
